package com.example.uilearning;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class HandlerActivity extends Activity {
	private EditText editText;
	private Button btton;

	class CalThread extends Thread {
		public Handler handler;

		@Override
		public void run() {
			Looper.prepare();
			handler = new Handler() {

				@Override
				public void handleMessage(Message msg) {
					if (msg.what == 0x123) {
						int upper = msg.getData().getInt("upper");
						List<Integer> nums = new ArrayList<Integer>();
						outer: for (int i = 2; i <= upper; i++) {
							// 用i除以从2开始到i的平方根的所有数
							for (int j = 2; j <= Math.sqrt(i); j++) {
								if (i != 2 && i % j == 0) {
									continue outer;
								}
							}
							nums.add(i);
						}
						Toast.makeText(HandlerActivity.this, nums.toString(),
								Toast.LENGTH_LONG).show();

					}
				}
			};
			Looper.loop();
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_handler);
		editText = (EditText) findViewById(R.id.upper);
		btton = (Button) findViewById(R.id.calButton);
		final CalThread calThread = new CalThread();
		calThread.start();
		btton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Message msg = new Message();
				msg.what = 0x123;
				Bundle bundle = new Bundle();
				bundle.putInt("upper",
						Integer.parseInt(editText.getText().toString()));
				msg.setData(bundle);
				//向新线程发送消息
				calThread.handler.sendMessage(msg);
			}
		});
	}

}
